<template>
  <wd-popup v-model="visible" position="bottom" :style="{ height: '75%' }">
    <view class="expense-form">
      <view class="form-header">
        <text class="form-title">{{ isEdit ? "编辑支出" : "添加支出" }}</text>
        <view class="header-actions">
          <wd-icon name="check" size="20px" color="#FF8C00" class="save-icon" :loading="loading" @click="submit"></wd-icon>
          <wd-icon name="close" size="20px" @click="cancel"></wd-icon>
        </view>
      </view>

      <view class="form-content">
        <view class="form-item">
          <text class="form-label">金额</text>
          <wd-input v-model="formData.amount" type="number" placeholder="请输入支出金额" clearable></wd-input>
        </view>

        <view class="form-item">
          <text class="form-label">分类</text>
          <scroll-view scroll-x class="category-scroll" show-scrollbar="false">
            <view class="category-list">
              <view
                v-for="category in categories.filter((c) => c.id !== 'all')"
                :key="category.id"
                class="category-item"
                :class="{ active: formData.category === category.id }"
                @click="selectCategory(category.id)"
              >
                <expense-category-icon :icon-name="category.id"></expense-category-icon>
                <text class="category-name">{{ category.name }}</text>
              </view>
            </view>
          </scroll-view>
        </view>

        <view class="form-item">
          <text class="form-label">描述</text>
          <wd-input v-model="formData.description" placeholder="请输入支出描述" clearable></wd-input>
        </view>

        <view class="form-item">
          <text class="form-label">日期</text>
          <view style="width: 0; height: 0; overflow: hidden">
            <wd-datetime-picker
              ref="datePicker"
              v-model="formData.date"
              label=""
              type="date"
              format="YYYY-MM-DD"
              value-format="timestamp"
              :max="maxDate"
              @confirm="onDateConfirm"
            ></wd-datetime-picker>
          </view>
          <view @click="openDatePicker">
            <wd-input readonly :model-value="formatDate(formData.date)" placeholder="请选择日期" right-icon="calendar"></wd-input>
          </view>
        </view>

        <view class="form-item">
          <text class="form-label">备注</text>
          <wd-textarea v-model="formData.remark" placeholder="请输入备注信息（选填）" :maxlength="200" show-count :rows="2"></wd-textarea>
        </view>
      </view>
    </view>
  </wd-popup>
</template>

<script>
import { EXPENSE_CATEGORIES } from "../stores/expense.js";
import ExpenseCategoryIcon from "./ExpenseCategoryIcon.vue";

export default {
  name: "ExpenseForm",
  components: {
    ExpenseCategoryIcon,
  },
  props: {
    show: {
      type: Boolean,
      default: false,
    },
    expense: {
      type: Object,
      default: null,
    },
  },
  data() {
    return {
      visible: false,
      loading: false,
      categories: EXPENSE_CATEGORIES,
      formData: {
        amount: "",
        category: "food",
        description: "",
        date: Date.now(),
        remark: "",
      },
      maxDate: Date.now(),
    };
  },
  computed: {
    isEdit() {
      return !!this.expense;
    },
  },
  watch: {
    show(val) {
      this.visible = val;
      if (val) {
        this.initForm();
      }
    },
    visible(val) {
      this.$emit("update:show", val);
    },
  },
  methods: {
    initForm() {
      if (this.expense) {
        // 编辑模式，填充表单数据
        this.formData = {
          amount: this.expense.amount.toString(),
          category: this.expense.category,
          description: this.expense.description,
          date: new Date(this.expense.date).getTime(),
          remark: this.expense.remark || "",
        };
      } else {
        // 添加模式，重置表单
        this.formData = {
          amount: "",
          category: "food",
          description: "",
          date: Date.now(),
          remark: "",
        };
      }
    },
    selectCategory(categoryId) {
      this.formData.category = categoryId;
    },
    openDatePicker() {
      this.$refs.datePicker.open();
    },
    onDateConfirm({ value }) {
      this.formData.date = value;
    },
    formatDate(timestamp) {
      if (!timestamp) return "";
      const date = new Date(timestamp);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const day = String(date.getDate()).padStart(2, "0");
      return `${year}-${month}-${day}`;
    },
    validateForm() {
      if (!this.formData.amount || isNaN(parseFloat(this.formData.amount))) {
        uni.showToast({
          title: "请输入有效金额",
          icon: "none",
        });
        return false;
      }

      if (!this.formData.description) {
        uni.showToast({
          title: "请输入支出描述",
          icon: "none",
        });
        return false;
      }

      return true;
    },
    submit() {
      if (!this.validateForm()) return;

      this.loading = true;

      // 构建提交数据
      const submitData = {
        amount: parseFloat(this.formData.amount),
        category: this.formData.category,
        description: this.formData.description,
        date: new Date(this.formData.date).toISOString(),
        remark: this.formData.remark,
      };

      // 模拟网络延迟
      setTimeout(() => {
        this.$emit("submit", submitData);
        this.loading = false;
        this.cancel();
      }, 300);
    },
    cancel() {
      this.visible = false;
    },
  },
};
</script>

<script setup>
// Vue 3 setup script
</script>

<style lang="scss" scoped>
.expense-form {
  display: flex;
  flex-direction: column;
  height: 100%;
  background-color: #fff;
  border-radius: 16px 16px 0 0;
}

.form-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  border-bottom: 1px solid #eee;

  .form-title {
    font-size: 18px;
    font-weight: 500;
    color: #333;
  }

  .header-actions {
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 60px;

    .save-icon {
      padding: 5px;
    }

    .wd-icon {
      padding: 5px;
    }
  }
}

.form-content {
  flex: 1;
  padding: 15px 15px 30px;
  overflow-y: auto;
}

.form-item {
  margin-bottom: 20px;

  .form-label {
    display: block;
    font-size: 14px;
    color: #666;
    margin-bottom: 8px;
  }
}

.category-scroll {
  width: 100%;
  white-space: nowrap;
}

.category-list {
  display: inline-flex;
  padding: 5px 0;
}

.category-item {
  display: inline-flex;
  flex-direction: column;
  align-items: center;
  padding: 10px;
  margin-right: 15px;
  border-radius: 8px;
  transition: all 0.3s;

  &.active {
    background-color: #fff0e0;

    .category-name {
      color: #ff8c00;
    }
  }

  .category-icon {
    margin-bottom: 6px;
    width: 40px;
    height: 40px;
    border-radius: 50%;
    background-color: #f5f5f5;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .category-name {
    font-size: 12px;
    color: #666;
  }
}
</style>
